from db.util import DBconn


# 查询
def db_query(p_sql):
    conn = ''
    db_cursor = ''
    v_sql = p_sql
    if len(v_sql.strip()) > 0:
        try:
            conn, db_cursor = DBconn.conn_db()
            db_cursor.execute(v_sql)
            result = db_cursor.fetchall()
        except Exception as e:
            print(e)
        finally:
            conn.close()
            db_cursor.close()
            return result
    else:
        return None


# 删除
def db_delete(p_sql):
    conn = ''
    db_cursor = ''
    v_sql = p_sql
    if len(v_sql.strip()) > 0:
        try:
            conn, db_cursor = DBconn.conn_db()
            conn.start_transaction()
            db_cursor.execute(v_sql)
            conn.commit()
            print("SQL:", db_cursor.statement)
            return db_cursor.rowcount
        except Exception as e:
            print(e)
            conn.rollback()
        finally:
            conn.close()
            db_cursor.close()
    else:
        return 0


# 更新
def db_update(p_sql):
    conn = ''
    db_cursor = ''
    v_sql = p_sql
    if len(v_sql.strip()) > 0:
        try:
            conn, db_cursor = DBconn.conn_db()
            conn.start_transaction()
            db_cursor.execute(v_sql)
            conn.commit()
            print("SQL:", db_cursor.statement)
            return db_cursor.rowcount
        except Exception as e:
            print(e)
            conn.rollback()
        finally:
            conn.close()
            db_cursor.close()
    else:
        return 0


# 插入
def db_insert(p_sql, p_value):
    conn = ''
    db_cursor = ''
    v_sql = p_sql
    v_values = p_value
    if len(v_sql.strip()) > 0:
        try:
            conn, db_cursor = DBconn.conn_db()
            db_cursor.executemany(v_sql, v_values)
            conn.commit()
            print("SQL:", db_cursor.statement)
            return db_cursor.rowcount
        except Exception as e:
            print(e)
        finally:
            conn.close()
            db_cursor.close()
    else:
        return 0
